from splinter.browser import Browser
from time import sleep
import traceback


class Buy_Tickets(object):
    # 定义实例属性，初始化
    def __init__(self, username, passwd, order, passengers, dtime, starts, ends):
        self.username=username
        self.passwd=passwd
        # 车次 0代表所有车次 依次从上到下，
        self.order=order
        # 乘客名
        self.passengers=passengers
        # 起始点和重点
        self.starts=starts
        self.ends=ends
        #日期
        self.dtime=dtime
        self.login_url='https://kyfw.12306.cn/otn/login/init'
        self.initMy_url = 'https://kyfw.12306.cn/otn/index/initMy12306'
        self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init'
        self.driver_name='chrome'
        self.executable_path=r'C:\Users\Administrator\AppData\Local\Programs\Python\Python36\Scripts\chromedriver.exe'
    def login(self):
        self.driver.visit(self.login_url)
        self.driver.fill('loginUserDTO.user_name',self.username)
        self.driver.fill('userDTO.password',self.passwd)
        print('请输入验证码')
        while True:
            if self.driver.url!=self.initMy_url:
                sleep(1)
            else:
                break

    def start_buy(self):
        self.driver=Browser(driver_name=self.driver_name,executable_path=self.executable_path)
        self.driver.driver.set_window_size(700,500)
        self.login()
        self.driver.visit(self.ticket_url)
        try:
            print('开始购票')
            # 加载查询信息
            self.driver.cookies.add({"_jc_save_fromStation": self.starts})
            self.driver.cookies.add({"_jc_save_toStation": self.ends})
            self.driver.cookies.add({"_jc_save_fromDate": self.dtime})
            self.driver.reload()
            count=0
            if self.order!=0:
                while self.driver.url == self.ticket_url:
                    self.driver.find_by_text('查询').click()
                    count+=1
                    print('第%d次查询。。' % count)
                    try:
                        self.driver.find_by_text('预订')[self.order-1].click()
                        sleep(1.5)
                    except Exception as e:
                        print(e)
                        print('预订失败')
                        continue
            else:
                while self.driver.url == self.ticket_url:
                    self.driver.find_by_text('查询').click()
                    count+=1
                    print('第%d此点击' % count)
                    try:
                        for i in self.driver.find_by_text('预订'):
                            i.click()
                            sleep(1)
                    except Exception as e:
                        print(e)
                        print('预订失败。。。')
                        continue

            print('开始预订。。。')
            sleep(1)
            print('开始选择用户...')
            for p in self.passengers:

                self.driver.find_by_text(p).last.click()
                sleep(0.5)
                if p[-1] == ')':
                    self.driver.find_by_id('dialog_xsertcj_ok').click()

            print('提交订单...')

            self.driver.find_by_id('submitOrder_id').click()
            sleep(2)
            print('确认选座')
            self.driver.find_by_id('qr_submit_id').click()
            print('预订成功...')
        except Exception as e:
            traceback.print_exc()


if __name__ == '__main__':
    # 用户名
    username='xx'

    #密码
    password='xx'

    order = 3

    passengers=['xx']

    # 预订的时间
    dtime= '2018-01-25'
    # 可以通过fiddler看到cookie的值
    starts='%u5357%u4EAC%2CNJH'
    # 重点的cookie
    ends='%u6CF0%u5DDE%2CUTH'

    Buy_Tickets(username,password,order,passengers,dtime,starts,ends).start_buy()



if __name__ == '__main__':
    driver=Browser(driver_name='chrome',executable_path=r'C:\Users\Administrator\AppData\Local\Programs\Python\Python36\Scripts\chromedriver.exe')
